///////////////////////////////
// Main Program
///////////////////////////////
#define SmearingClass_h
#include <iostream>
#include <fstream>
#include <stdlib.h>  //atoi
#include <unistd.h>  //getopt
#include "CBNTanalyser.h"
#include "TChain.h"

int main(int argc, char** argv)
{
  int nevt = 0;       // 0 for all events, or use -n option
  int runoption = 1;  // 0 for Zee, 1 for Wenu, 2 for Zmumu, 3 for JPsiMumu
  TString filelist("file.list");

//  TChain ch("hanl/Preselection");
  TChain ch("ampt");

  int c;
  while( (c=getopt(argc,argv,"hn:n:t:s:")) != -1 ){
    switch(c){
    case 'h':
      std::cout << "Usage: " << argv[0]
                << " [-h] [-n <number_of_events>] "
                << " [-t 0-39]  [-s 11-45]"
                << std::endl;
      exit(0);
      break;
    case 'n':
      nevt = atoi(optarg);
      if (nevt < 0) nevt = 0;
      break;
    case 't':
      runoption = atoi(optarg);
      break;
      // case 's':
      //    smeartype = atoi(optarg);
      //   break;
    }
  }

  std::cout << "===========================================" << "\n"
            << "           Reading Files                   " << "\n"
            << "===========================================" << std::endl;

  TString input_roottuple;
  CBNTanalyser *sel = new CBNTanalyser;

  ifstream fin;
  fin.open(filelist.Data());
  Int_t sum=0;

  while( fin >> input_roottuple )
    {
      TFile *newROOTFile= new TFile( input_roottuple );
      TTree *SelEventROOTTree = (TTree *)newROOTFile->Get("ampt" );

      if(!SelEventROOTTree)
        std::cout << "Can not open ROOT file: " << input_roottuple << std::endl;
      else
        {
          std::cout << "File: " << input_roottuple << ", Entries = " << SelEventROOTTree->GetEntries() << std::endl;
          ch.Add(input_roottuple);
          sum++;
        }

      delete SelEventROOTTree;
      delete newROOTFile;
    }

  std::cout << "===========================================" << "\n"
            << "       " << sum << " file(s) is(are) merged" << "      " << "\n"
            << "===========================================" << std::endl;

  fin.close();


  std::cout << "===========================================" << "\n"
            << "           Analyzing  Files                   " << "\n"
            << "===========================================" << std::endl;

  if( nevt != 0 )
    ch.Process(sel, "", nevt);
  else
    ch.Process(sel, "");

}
